<?php
require('lib/verify.php');
require('lib/has_char.php');
require('lib/is_approved.php');
require('lib/is_admin.php');

function verify_names($names, $db, $system_id) {
  $nlook = array();
$exam = explode("\n", $names);
while(list($n, $name) = each($exam)) {
  $name = ucfirst(strtolower(trim($name)));
  $sql = "select * from wm_characters where character_system_id = $system_id and character_name='$name' and character_approved=1";
  $result = $db->query($sql);
  if($db->num_rows($result)!=1) {
    $err = "Unrecognized character '<b>$name</b>'.  Please make sure he or she is registered and approved.";
    header("Location: error.php?error=$err");
    exit;
  }
  $chara = $db->fetch_assoc($result);
  $nlook[$name] = $chara["character_id"];
}
 return $nlook;

}

$system_id = $system["system_id"];

$raid_id = $_POST["raid_id"];
$sql = "select * from wm_raids  left join wm_instances on wm_instances.instance_id = raid_instance where wm_raids.raid_system_id = $system_id and raid_id = $raid_id";

$result = $db->query($sql);
$raid = $db->fetch_assoc($result);

//verify the attendees
$attendance = $_POST["attendance"];
$satout = $_POST["satout"];

$name_lookup = verify_names($attendance, $db, $system_id);


if($satout!="") {
$satout_lookup = verify_names($satout, $db, $system_id);
}

//do the credit
$credit_raid = $_POST["raid_id"];

$month = $_POST["month"]+1;
$day = $_POST["day"];
$year = $_POST["year"];

$hour = $_POST["hour"];
$minute = $_POST["minute"];
$ampm = $_POST["ampm"];
if($minute<10) {
  $minute = "0" . $minute;
}

$date_string = "$month/$day/$year $hour:$minute:00 $ampm";
$credit_time = strtotime($date_string);

$credit_boss = $_POST["boss"];

$sql = "insert into wm_credits (credit_boss, credit_date, credit_raid, credit_system_id) values ('$credit_boss', FROM_UNIXTIME($credit_time), '$credit_raid', '$system_id')";
$result = $db->query($sql);

$ii = $db->insert_id($result);

//do attendance
while(list($name, $cid) = each($name_lookup)) {
  $sql = "insert into wm_attendees (attendee_character, attendee_credit, attendee_satout, attendee_system_id) values ('$cid', '$ii', '0', '$system_id')";
  $res = $db->query($sql);
}

if($satout!="") {
while(list($name, $cid) = each($satout_lookup)) {
  $sql = "insert into wm_attendees (attendee_character, attendee_credit, attendee_satout, attendee_system_id) values ('$cid', '$ii', '1', '$system_id')";
  $res = $db->query($sql);
}
}

//if($system["system_id"]!=1) {
reprocessDKP($db, $system["system_id"]);
//}

header("Location: add-loot.php?id=$ii");

?>